package week4th.jsjf;

import week4th.jsjf.exceptions.NonComparableElementException;

public class LinkedOrderedList<T> extends LinkedList<T>
         implements OrderedListADT<T>
{
    public LinkedOrderedList()
    {
        super();
    }

    public void add(T element)
    {
        if (!(element instanceof Comparable)) {
            throw new NonComparableElementException("LinkedList");
        }
        Comparable<T> comparableElement = (Comparable<T>)element;
        LinearNode node = new LinearNode(comparableElement);
        LinearNode last = head;
        for (int i = 1; i < count; i++) {
            last = last.getNext();
        }
        if (size() == 0) {
            head = node;
            tail = node;
            count++;
            return;
        } else if (comparableElement.compareTo(head.getElement()) < 0) {
            node.setNext(head);
            head = node;
            count++;
            return;
        } else if (comparableElement.compareTo((T) last.getElement()) > 0) {
            last.setNext(node);
            count++;
        } else {
            LinearNode current = head;
            LinearNode next = current.getNext();
            for (int i = 0; i < count - 1; i++) {
                if (comparableElement.compareTo((T) next.getElement()) < 0) {
                    current.setNext(node);
                    node.setNext(next);
                    count++;
                    return;
                }
                current = next;
                next = next.getNext();
            }
        }
    }
}
